import React, { useEffect, useState } from "react";
import "../Patient.css";
import axios from "axios";
import { Tabs, Input, Space, DatePicker, Button, Pagination } from "antd";
import type { TabsProps } from "antd";
import { DownloadOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';

interface Props {
    _id:string,
    door: string;
    card: string;
    name: string;
    keshi: string;
    doctor: string;
    money: string;
    status: string; // 状态：1-待确诊，2-已就诊，3-已退号，4-已失效
    simian: string;
}

const Content: React.FC<Props> = () => {
    const [doctor, setDoctor] = useState<Props[]>([]);
    const [activeTab, setActiveTab] = useState<string>("0"); // 当前选中的 Tab
    const { RangePicker } = DatePicker;
    const [dates, setDates] = useState([null, null]);
    const [size] = useState('large');
    // 就诊卡号搜素
    const [card, setcard] = useState("")
    // 患者搜索
    const [name, setname] = useState("")
    // 就诊号
    const [jiuzhen, setjiuzhen] = useState("")
    // 挂号医生
    const [dos, setdos] = useState("")
    // 挂号科室搜索
    const [keshi, setkeshi] = useState("")

    const [pages, setpages] = useState(1)
    const [num, setnum] = useState(1)
    const [numpage, setnumpage] = useState(1)
    const limit = 5  //每页条数
    // 获取数据
    const getList = (page: number) => {
        axios.get(`http://127.0.0.1:3000/cws/index_doctor/?card=${card}&name=${name}&jiuzhen=${jiuzhen}&dos=${dos}&keshi=${keshi}&page=${page}&limit=${limit}`).then((response) => {
            const { code, data, num, numpage } = response.data;
            if (code === 200) {
                setDoctor(data);
                setnum(num)
                setnumpage(numpage)
            }
        });
    };

    // 挂载数据
    useEffect(() => {
        getList(pages);
    }, [pages]);

    // Tabs 切换回调
    const onChange = (key: string) => {
        setActiveTab(key);
    };

    // Tabs 标签
    const items: TabsProps['items'] = [
        {
            key: '0',
            label: '全部挂号',
        },
        {
            key: '1',
            label: '待确诊',
        },
        {
            key: '2',
            label: '已就诊',
        },
        {
            key: '3',
            label: '已退号',
        },
        {
            key: '4',
            label: '已失效',
        },
    ];

    // 搜索
    const search = () => {
        getList(pages)
    }

    // 根据当前 Tab 过滤数据
    const filteredData = doctor.filter((item) => {
        if (activeTab === "0") {
            return true;
        } else if (activeTab === "1") {
            return item.status === "1";
        } else if (activeTab === "2") {
            return item.status === "2";
        } else if (activeTab === "3") {
            return item.status === "3";
        } else if (activeTab === "4") {
            return item.status === "4";
        }
        return true;
    });
    const onChange1 = (dates) => {
        setDates(dates);
    };
    // 分页
    const hangpage = (page: number) => {
        setpages(page)
    }
     
    // 取消挂号
    const del = () => {
        if (confirm("你确定要取消挂号吗?")) {
            axios.delete(`http://127.0.0.1:3000/del`, { data: { id: _id } }).then((response) => {
                const { code } = response.data;
                if (code === 200) {
                    getList(pages);
                }
            }).catch((error) => {
                console.error("删除失败:", error);
            });
        }
    };
    // 导出 Excel 文件
    const exportToExcel = () => {
        const headers = ['门(就)卡号', '处方号', '就诊卡号', '患者姓名', '开单科室', '开单医生', '缴费状态', '缴费金额', '收费时间'];
        const data = filteredData.map(item => [
            item.door,
            item.card,
            item.name,
            item.keshi,
            item.doctor,
            item.money,
            item.status, // 状态：1-待确诊，2-已就诊，3-已退号，4-已失效
            item.simian,
        ]);
        data.unshift(headers);

        const ws = XLSX.utils.aoa_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
        XLSX.writeFile(wb, 'patient_data.xlsx');
    };
    return (
        <div className="doctor">
            <div className="content_li">
                <span style={{ marginLeft: "60px" }}>就诊卡号:</span>&nbsp;
                <Input style={{ width: "250px" }} placeholder="请输入" onChange={(event) => {
                    setcard(event.target.value)
                }} />
                <span style={{ marginLeft: "180px" }} >患者姓名:</span>&nbsp;
                <Input style={{ width: "250px" }} placeholder="请输入" onChange={(event) => {
                    setname(event.target.value)
                }} />
                <span style={{ marginLeft: "270px" }}>证件号:</span>&nbsp;
                <Input style={{ width: "250px" }} placeholder="请输入" /><br></br><br></br>
                <span style={{ marginLeft: "60px" }}>就诊号:</span>&nbsp;
                <Input style={{ width: "250px" }} placeholder="请输入" onChange={(event) => {
                    setjiuzhen(event.target.value)
                }} />
                <span style={{ marginLeft: "180px" }}>缴费状态:</span>&nbsp;
                <Input style={{ width: "250px" }} placeholder="请输入" />
                <span style={{ marginLeft: "270px" }}>挂号时间:</span>&nbsp;
                <Space direction="vertical" size={12}>
                    <RangePicker
                        value={dates}
                        onChange={onChange1}
                        style={{ width: "250px" }}
                        format="YYYY-MM-DD HH:mm"
                        placeholder={['开始时间', '结束时间']}
                    />
                </Space><br></br><br></br>
                <span style={{ marginLeft: "60px" }}>挂号医生:</span>&nbsp;
                <Input style={{ width: "250px" }} placeholder="请输入" onChange={(event) => {
                    setdos(event.target.value)
                }} />
                <span style={{ marginLeft: "180px" }}>挂号科室:</span>&nbsp;
                <Input style={{ width: "250px" }} placeholder="请输入" onChange={(event) => {
                    setkeshi(event.target.value)
                }} />
                <div className="cui" style={{ width: "300px", marginLeft: "1200px", marginTop: "-35px" }}>
                    <Button type="primary" icon={<DownloadOutlined />} size={size} onClick={exportToExcel} />
                    <Button type="primary">重置</Button>
                    <Button type="primary" onClick={() => {
                        search()
                    }} >搜索</Button>
                </div>
            </div>
            <div>
                <Tabs
                    defaultActiveKey="0"
                    items={items}
                    onChange={onChange}
                    style={{ marginLeft: "250px", width: "1500px", backgroundColor: "white", marginTop: "60px", float: "left" }}
                />
            </div>

            <div className="doctor_in">
                <table style={{ backgroundColor: "rgb(242, 242, 242)", marginTop: "130px" }}>
                    <thead>
                        <tr>
                            <th>门(就)诊号</th>
                            <th>就诊卡号</th>
                            <th>患者姓名</th>
                            <th>挂号科室</th>
                            <th>挂号医生</th>
                            <th>挂号金额</th>
                            <th>挂号状态</th>
                            <th>挂号日期</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {filteredData.map((item, index) => (
                            <tr key={index} style={{ backgroundColor: "white",textAlign:"center" }}>
                                <td>{item.door}</td>
                                <td>{item.card}</td>
                                <td>{item.name}</td>
                                <td>{item.keshi}</td>
                                <td>{item.doctor}</td>
                                <td>{item.money}</td>
                                <td>
                                    {item.status === "1" && (
                                        <span style={{ color: "orange", fontWeight: "bold" }}>待确诊</span>
                                    )}
                                    {item.status === "2" && (
                                        <span style={{ color: "green", fontWeight: "bold" }}>已就诊</span>
                                    )}
                                    {item.status === "3" && (
                                        <span style={{ color: "red", fontWeight: "bold" }}>已退号</span>
                                    )}
                                    {item.status === "4" && (
                                        <span style={{ color: "gray", fontWeight: "bold" }}>已失效</span>
                                    )}
                                </td>
                                <td>{item.simian}</td>
                                <td className="content_main">
                                    <span>详情</span>
                                    <span onClick={()=>{
                                        del(item._id)
                                    }}>取消挂号</span>
                                    <span>更多 <span style={{ fontSize: "15px", marginTop: "-18px" }}>v</span></span>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                <div className="page">
                    <div style={{
                        width: "500px", marginLeft: "900px", height: "100px"
                    }}>
                        <span style={{ float: "left", lineHeight: "30px", "color": "blue" }}>共有{num}数据</span>
                        <Pagination showQuickJumper defaultCurrent={numpage} total={num} pageSize={limit} onChange={hangpage} />
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Content;